import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Level, Badge, PlayerProgress, LevelStatus, LevelDifficulty, LevelType } from '@/types/game'
import { LevelStatus as Status, LevelDifficulty as Difficulty, LevelType as Type } from '@/types/game'

export const useGameStore = defineStore('game', () => {
  // 状态
  const playerProgress = ref<PlayerProgress>({
    currentLevel: 1,
    totalStars: 0,
    badges: [],
    completedLevels: []
  })

  // 所有关卡配置
  const levels = ref<Level[]>([
    // 初级关卡
    { id: 1, name: '认识数字 0-5', type: Type.NUMBER_RECOGNITION, difficulty: Difficulty.BEGINNER, status: Status.UNLOCKED, stars: 0, position: { x: 100, y: 400 } },
    { id: 2, name: '认识数字 6-9', type: Type.NUMBER_RECOGNITION, difficulty: Difficulty.BEGINNER, status: Status.LOCKED, stars: 0, position: { x: 200, y: 350 }, requiredLevel: 1 },
    { id: 3, name: '形状匹配', type: Type.SHAPE_MATCHING, difficulty: Difficulty.BEGINNER, status: Status.LOCKED, stars: 0, position: { x: 300, y: 300 }, requiredLevel: 2 },
    { id: 4, name: '比大小', type: Type.COMPARE_SIZE, difficulty: Difficulty.BEGINNER, status: Status.LOCKED, stars: 0, position: { x: 400, y: 250 }, requiredLevel: 3 },

    // 中级关卡
    { id: 5, name: '加法乐园', type: Type.ADDITION, difficulty: Difficulty.INTERMEDIATE, status: Status.LOCKED, stars: 0, position: { x: 500, y: 200 }, requiredLevel: 4 },
    { id: 6, name: '减法世界', type: Type.SUBTRACTION, difficulty: Difficulty.INTERMEDIATE, status: Status.LOCKED, stars: 0, position: { x: 600, y: 150 }, requiredLevel: 5 },
    { id: 7, name: '找规律', type: Type.PATTERN, difficulty: Difficulty.INTERMEDIATE, status: Status.LOCKED, stars: 0, position: { x: 700, y: 100 }, requiredLevel: 6 },

    // 高级关卡
    { id: 8, name: '逻辑推理', type: Type.LOGIC, difficulty: Difficulty.ADVANCED, status: Status.LOCKED, stars: 0, position: { x: 800, y: 150 }, requiredLevel: 7 },
    { id: 9, name: '认识时间', type: Type.TIME, difficulty: Difficulty.ADVANCED, status: Status.LOCKED, stars: 0, position: { x: 900, y: 200 }, requiredLevel: 8 },
    { id: 10, name: '认识钱币', type: Type.MONEY, difficulty: Difficulty.ADVANCED, status: Status.LOCKED, stars: 0, position: { x: 1000, y: 250 }, requiredLevel: 9 }
  ])

  // 可用徽章
  const availableBadges = ref<Badge[]>([
    { id: 'first_star', name: '第一颗星', icon: '⭐', description: '获得第一颗星星', unlocked: false },
    { id: 'number_master', name: '数字大师', icon: '🔢', description: '完成所有数字关卡', unlocked: false },
    { id: 'shape_expert', name: '形状专家', icon: '🔷', description: '完成形状匹配', unlocked: false },
    { id: 'math_genius', name: '数学天才', icon: '🧮', description: '完成所有加减法关卡', unlocked: false },
    { id: 'logic_master', name: '逻辑大师', icon: '🧠', description: '完成所有逻辑关卡', unlocked: false },
    { id: 'all_complete', name: '探险完成', icon: '🏆', description: '完成所有关卡', unlocked: false }
  ])

  // 计算属性
  const unlockedLevels = computed(() =>
    levels.value.filter(level => level.status !== Status.LOCKED)
  )

  const completedLevelsCount = computed(() =>
    levels.value.filter(level => level.status === Status.COMPLETED).length
  )

  const unlockedBadges = computed(() =>
    availableBadges.value.filter(badge => badge.unlocked)
  )

  // 方法
  function completeLevel(levelId: number, stars: number) {
    const level = levels.value.find(l => l.id === levelId)
    if (!level) return

    // 更新关卡状态
    level.status = Status.COMPLETED
    level.stars = Math.max(level.stars, stars)

    // 更新玩家进度
    if (!playerProgress.value.completedLevels.includes(levelId)) {
      playerProgress.value.completedLevels.push(levelId)
    }
    playerProgress.value.totalStars += stars

    // 解锁下一关
    const nextLevel = levels.value.find(l => l.requiredLevel === levelId)
    if (nextLevel) {
      nextLevel.status = Status.UNLOCKED
    }

    // 检查徽章
    checkBadges()

    // 保存进度
    saveProgress()
  }

  function checkBadges() {
    // 第一颗星
    if (playerProgress.value.totalStars >= 1 && !availableBadges.value[0].unlocked) {
      unlockBadge('first_star')
    }

    // 数字大师
    const numberLevels = levels.value.filter(l => l.type === Type.NUMBER_RECOGNITION)
    if (numberLevels.every(l => l.status === Status.COMPLETED)) {
      unlockBadge('number_master')
    }

    // 形状专家
    const shapeLevels = levels.value.filter(l => l.type === Type.SHAPE_MATCHING)
    if (shapeLevels.every(l => l.status === Status.COMPLETED)) {
      unlockBadge('shape_expert')
    }

    // 数学天才
    const mathLevels = levels.value.filter(l =>
      l.type === Type.ADDITION || l.type === Type.SUBTRACTION
    )
    if (mathLevels.every(l => l.status === Status.COMPLETED)) {
      unlockBadge('math_genius')
    }

    // 逻辑大师
    const logicLevels = levels.value.filter(l => l.type === Type.LOGIC)
    if (logicLevels.every(l => l.status === Status.COMPLETED)) {
      unlockBadge('logic_master')
    }

    // 探险完成
    if (levels.value.every(l => l.status === Status.COMPLETED)) {
      unlockBadge('all_complete')
    }
  }

  function unlockBadge(badgeId: string) {
    const badge = availableBadges.value.find(b => b.id === badgeId)
    if (badge && !badge.unlocked) {
      badge.unlocked = true
      badge.unlockedAt = new Date()
      playerProgress.value.badges.push(badge)
    }
  }

  function saveProgress() {
    localStorage.setItem('mathIsland_progress', JSON.stringify({
      playerProgress: playerProgress.value,
      levels: levels.value,
      badges: availableBadges.value
    }))
  }

  function loadProgress() {
    const saved = localStorage.getItem('mathIsland_progress')
    if (saved) {
      try {
        const data = JSON.parse(saved)
        playerProgress.value = data.playerProgress
        levels.value = data.levels
        availableBadges.value = data.badges
      } catch (e) {
        console.error('加载进度失败:', e)
      }
    }
  }

  function resetProgress() {
    localStorage.removeItem('mathIsland_progress')
    playerProgress.value = {
      currentLevel: 1,
      totalStars: 0,
      badges: [],
      completedLevels: []
    }
    // 重置关卡状态
    levels.value.forEach((level, index) => {
      level.status = index === 0 ? Status.UNLOCKED : Status.LOCKED
      level.stars = 0
    })
    // 重置徽章
    availableBadges.value.forEach(badge => {
      badge.unlocked = false
      badge.unlockedAt = undefined
    })
  }

  return {
    playerProgress,
    levels,
    availableBadges,
    unlockedLevels,
    completedLevelsCount,
    unlockedBadges,
    completeLevel,
    unlockBadge,
    saveProgress,
    loadProgress,
    resetProgress
  }
})
